package com.uetoken.cn.activity;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.MessageCenterAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.CustomMailsBean;
import com.uetoken.cn.bean.MailsBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * 消息中心
 */
public class MessageCenterActivity extends BaseActivity implements WebResponse{

    @BindView(R.id.iv_activity_message_center_back)
    ImageView    mIvBack;
    @BindView(R.id.tv_activity_message_center_title)
    TextView     mTvTitle;
    @BindView(R.id.ry_activity_message_content)
    RecyclerView mRyContent;
    @BindView(R.id.tv_activity_message_edit)
    TextView     mTvEdit;
    @BindView(R.id.rl_activity_message_no)
    RelativeLayout mRlNoContent;

    @BindView(R.id.cb_item_message_center_foot_all_select)
    CheckBox footCheckBox;
    @BindView(R.id.tv_item_message_center_foot_delete)
    TextView mTvDelete;
    @BindView(R.id.tv_item_message_center_foot_have_read)
    TextView mTvHaveRead;
    @BindView(R.id.ll_all_select)
    LinearLayout mLlAllSelect;

    private List<CustomMailsBean> mMessageCenterBeanList = new ArrayList<>();
    private MessageCenterAdapter mAdapter;

    /**
     * 编辑状态
     */
    private boolean   editorStatus = false;
    /**
     * 不可编辑模式状态码
     */
    private static final int MODE_CHECK = 0;
    /**
     * 可编辑模式状态码
     */
    private static final int MODE_EDIT = 1;

    private int mEditMode = MODE_CHECK;
    /**
     * 请求消息的网络请求码
      */
    private static final int NETWORK_REQUEST_MAILS = 10;
    /**
     * 修改消息为已读的网络请求码
     */
    private static final int NETWORK_REQUEST_EDTI_MAIL_STATUS = 20;
    /**
     * 通过一个一个点击item选中(不是通过全选按钮选中)的标识
      */
    private boolean oneByOneSelect = false;
    /**
     * 选中的item个数
     */
    private int selectItems = 0;



    @Override
    public int getLayoutId() {
        return R.layout.activity_message_center;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        mLlAllSelect.setVisibility(View.GONE);

        mTvTitle.setText(getString(R.string.tv_message_center));
        mRyContent.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    @Override
    public void initData() {

        mAdapter = new MessageCenterAdapter(R.layout.item_message_center, mMessageCenterBeanList);
        mRyContent.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                final CustomMailsBean customMailsBean = mMessageCenterBeanList.get(position);
                if (editorStatus){
                    oneByOneSelect = true;
                    //编辑状态下
                    boolean isSelect = customMailsBean.isSelect();
                    if (isSelect){
                        customMailsBean.setSelect(false);
                        selectItems--;
                    }else{
                        selectItems++;
                        customMailsBean.setSelect(true);
                    }
                    //一个一个的选中,当选中的条目个数和消息size一样大时,设置全选按钮为选中状态
                    if (selectItems==mMessageCenterBeanList.size()){
                        footCheckBox.setChecked(true);
                    }else {
                        footCheckBox.setChecked(false);
                    }
                    mAdapter.notifyDataSetChanged();
                }else {
                    //不可编辑状态下点击item直接弹窗
                    new QMUIDialog.MessageDialogBuilder(MessageCenterActivity.this).setTitle(customMailsBean.getTitle())
                            .setMessage(customMailsBean.getContent()).addAction(getResources().getString(R.string.str_known), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            //未读状态才回去调用接口变为已读
                            if (customMailsBean.getStatus()==0){
                                customMailsBean.setStatus(1);
                                mAdapter.notifyDataSetChanged();

                                //点击知道了直接调用接口修改为已读
                                editMailStatus(String.valueOf(customMailsBean.getHisid()),"1");
                            }

                        }
                    }).show();
                }
            }
        });

        footCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mAdapter==null){
                    return;
                }
                if (isChecked){
                    //全选后这个值也要变成false
                    oneByOneSelect = false;
                    selectItems = mMessageCenterBeanList.size();
                    for (int i = 0; i < mMessageCenterBeanList.size(); i++) {
                        mMessageCenterBeanList.get(i).setSelect(true);
                    }
                }else{
                    if (oneByOneSelect){

                    }else{
                        //取消全选后这个值变为0
                        selectItems = 0;
                        //单独点击的全选按钮全部设置选中状态为false
                        for (int i = 0; i < mMessageCenterBeanList.size(); i++) {
                            mMessageCenterBeanList.get(i).setSelect(false);
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getMailsUrl(),NETWORK_REQUEST_MAILS, Params.getMainsParams("0"));
    }

    @Override
    public void init() {

    }

    /**
     *
      * @param hisids
     * 修改站内信息为已读
     */
    private void editMailStatus(String hisids,String status){
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(MessageCenterActivity.this,ApiHelper.getEditMailStatusUrl(),NETWORK_REQUEST_EDTI_MAIL_STATUS,
                Params.getEditMainStatusParams(hisids,status));
    }

    @OnClick({R.id.iv_activity_message_center_back, R.id.tv_activity_message_edit,R.id.tv_item_message_center_foot_delete,R.id.tv_item_message_center_foot_have_read})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_activity_message_center_back:
                finish();
                break;
            case R.id.tv_activity_message_edit:
                updateEditMode();
                break;
            case R.id.tv_item_message_center_foot_delete:
                deleteMessage();
                break;
            case R.id.tv_item_message_center_foot_have_read:
                haveReadMessage();
                break;
        }
    }

    /**
     * 删除消息
     */
    private void deleteMessage() {
        //是否有选中的item
        boolean isSelectItem = false;
        for (int i = mMessageCenterBeanList.size(),j=0; i > j; i--) {
            CustomMailsBean customMailsBean = mMessageCenterBeanList.get(i-1);
            if (customMailsBean.isSelect()){
                isSelectItem = true;
                break;
            }
        }
        //说明有条目被选中,弹出是否删除对话框
        if (isSelectItem){
            new QMUIDialog.MessageDialogBuilder(this).setTitle(getResources().getString(R.string.str_delete_message)).setMessage(getResources().getString(R.string.str_delete_current_message))
                    .addAction(getResources().getString(R.string.str_cancel), new QMUIDialogAction.ActionListener() {

                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }).addAction(getResources().getString(R.string.str_confirm), new QMUIDialogAction.ActionListener() {
                @Override
                public void onClick(QMUIDialog dialog, int index) {
                    dialog.dismiss();
                    StringBuffer stringBufferHisid = new StringBuffer();
                    for (int i = mMessageCenterBeanList.size(),j=0; i > j; i--) {
                        CustomMailsBean customMailsBean = mMessageCenterBeanList.get(i-1);
                        if (customMailsBean.isSelect()){
                            stringBufferHisid.append(customMailsBean.getHisid()+",");
                            mMessageCenterBeanList.remove(customMailsBean);
                        }
                    }

                    if (mMessageCenterBeanList.size()==0){
                        mLlAllSelect.setVisibility(View.GONE);
                        mRlNoContent.setVisibility(View.VISIBLE);
                        mTvEdit.setVisibility(View.GONE);
                    }
                    final String selectItemStr = stringBufferHisid.toString();
                    //说明选择的条目不为空,调用接口删除消息
                    if (!TextUtils.isEmpty(selectItemStr)){
                        updateEditMode();
                        //调用接口删除消息
                        String hisIds = selectItemStr.substring(0,selectItemStr.length()-1);
                        editMailStatus(hisIds,"-1");
                    }
                }
            }).show();
        }
    }

    /**
     * 消息已读
     */
    private void haveReadMessage() {
        //是否有选中的Item
        boolean isSelctItem = false;
        StringBuffer stringBufferHisid = new StringBuffer();
        for (int i = mMessageCenterBeanList.size(),j=0; i > j; i--) {
            CustomMailsBean customMailsBean = mMessageCenterBeanList.get(i-1);
            if (customMailsBean.isSelect()){
                isSelctItem = true;
                if (customMailsBean.getStatus()==0){
                    stringBufferHisid.append(customMailsBean.getHisid()+",");
                }
                //如果点击了已读则设置状态全部为1
                customMailsBean.setStatus(1);
            }
        }

        //不为空说明选择的条目包含未读消息,调用接口变为已读
        if (!TextUtils.isEmpty(stringBufferHisid.toString())){
            //调用接口变更消息为已读
            String hisIds = stringBufferHisid.toString().substring(0,stringBufferHisid.toString().length()-1);
            editMailStatus(hisIds,"1");
        }

        if (isSelctItem){
            //变更编辑模式
            updateEditMode();
        }
    }

    /**
     * 变更编辑模式
     */
    private void updateEditMode() {
        mEditMode = mEditMode == MODE_CHECK? MODE_EDIT:MODE_CHECK;
        if (mEditMode==MODE_EDIT){
            mLlAllSelect.setVisibility(View.VISIBLE);
            mTvEdit.setText(getString(R.string.str_cancel_edit));
            editorStatus = true;
        }else{
            footCheckBox.setChecked(false);
            mLlAllSelect.setVisibility(View.GONE);
            mTvEdit.setText(getString(R.string.str_edit));
            editorStatus = false;
            for (int i = 0; i < mMessageCenterBeanList.size(); i++) {
                //取消编辑设置选中状态全部为未选中
                mMessageCenterBeanList.get(i).setSelect(false);
            }
        }
        //初始化这两个值
        oneByOneSelect = false;
        selectItems = 0;

        mAdapter.setEditMode(mEditMode);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        dissmissDialog();
        switch (requestCode){
            case NETWORK_REQUEST_MAILS:
                MailsBean mailsBean = new Gson().fromJson(response,MailsBean.class);
                if (mailsBean.getResult()>0) {
                    List<MailsBean.DataBean> dataBeans = mailsBean.getData();
                    if (dataBeans.size()>0){
                        mRlNoContent.setVisibility(View.GONE);
                        mTvEdit.setVisibility(View.VISIBLE);

                        for (int i = 0; i < dataBeans.size(); i++) {
                            CustomMailsBean customMailsBean = new CustomMailsBean();
                            customMailsBean.setTitle(dataBeans.get(i).getTitle());
                            customMailsBean.setContent(dataBeans.get(i).getContent());
                            customMailsBean.setHisid(dataBeans.get(i).getHisid());
                            customMailsBean.setStatus(dataBeans.get(i).getStatus());
                            customMailsBean.setCreatetime(dataBeans.get(i).getCreatetime());
                            customMailsBean.setSelect(false);
                            mMessageCenterBeanList.add(customMailsBean);
                        }
                        mAdapter.notifyDataSetChanged();
                    }else{
                        mRlNoContent.setVisibility(View.VISIBLE);
                        mTvEdit.setVisibility(View.GONE);
                    }
                }

                break;
            case NETWORK_REQUEST_EDTI_MAIL_STATUS:
                break;

        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }
}
